package com.xqls.biz.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xqls.bean.AlarmBean;
import com.xqls.bean.LevelTimeBean;
import com.xqls.biz.AlarmBiz;
import com.xqls.biz.MessageBiz;
import com.xqls.dal.model.AlarmExample;
import com.xqls.dal.model.Dictionary;
import com.xqls.service.AlarmService;
import com.xqls.service.DictionaryService;
import com.xqls.service.MessageService;
import com.xqls.service.UserService;
import com.xqls.util.CommonResult;
import com.xqls.util.DictionaryEnums;

@Service
public class AlarmBizImpl implements AlarmBiz {

	@Autowired
	private AlarmService alarmService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private MessageBiz messageBiz;
	@Autowired
	private UserService userService;
	@Autowired
	private DictionaryService dictionaryService;
	private static Logger logger = Logger.getLogger(AlarmBiz.class);

	@Override
	public CommonResult sendMessage(String deviceNo, int alarmType, DictionaryEnums alarmStatus) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date currect = new Date();
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			// 判断alarmType报警类型是否启动
			if (messageBiz.judgeLevelType(alarmType)) {
				String alarmTimeStr = format.format(currect);
				map = judgeTimes(deviceNo, alarmType, alarmStatus);
				// 取得符合这些条件的最小时间
				switch (alarmStatus) {
				case ALARM:
					// 如果当前时间差大于等于设定间隔时间
					alarm(format, alarmType, deviceNo, map);
					break;
				case NO_ALARM:
					noAlarm(format, alarmType, deviceNo, 0);
				}
			}
		} catch (Exception e) {
			logger.error("发送短信异常", e);
		}

		return null;
	}

	/**
	 * 
	 * @param deviceNo
	 * @param alarmType
	 * @param alarmStatus
	 * @return 次数，报警时间，间隔时间，相差分钟
	 */
	private Map<String, Object> judgeTimes(String deviceNo, int alarmType, DictionaryEnums alarmStatus) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		AlarmExample example = new AlarmExample();
		int intervalTime = 0;
		Map<String, Object> map = new HashMap<String, Object>();
		// 间隔时间
		Dictionary dictionary = dictionaryService.queryDictionaryById(DictionaryEnums.INTERVAL_TIME.getCode());
		if (dictionary != null) {
			intervalTime = Integer.parseInt(dictionary.getDictionaryValue());
		}
		example.createCriteria().andDeviceNoEqualTo(deviceNo).andAlarmTypeEqualTo(alarmType)
				.andAlarmStatusEqualTo(DictionaryEnums.ALARM.getCode());
		List<AlarmBean> list = alarmService.selAlarmByExample(example);// 得到次数和报警时间
		if (list != null && list.size() > 0) {
			for (AlarmBean alarmBean : list) {
				map.put("times", alarmBean.getTimes());
				map.put("initialAlarmTime", format.format(alarmBean.getInitialAlarmTime()));// 初始报警时间
				map.put("alarmTime", alarmBean.getAlarmTime());
				map.put("minute", (System.currentTimeMillis() - alarmBean.getInitialAlarmTime().getTime()) / 1000 / 60);// 当前时间与原始报警时间差
			}
		}
		map.put("intervalTime", intervalTime);
		return map;
	}

	private void noAlarm(SimpleDateFormat format, int alarmType, String deviceNo, int times) throws Exception {
		// 1看是否有该设备的报警信息 如果有,将状态改成报警已经解决
		alarmService.updateAlarmStatus(deviceNo, alarmType, DictionaryEnums.ALARM.getCode(), times);
	}

	private void sendMessage(int alarmType, String deviceNo, int times, Map<String, Object> oldMap) throws Exception {
		// 获取 1级报警持续时间，2级报警持续时间，3级报警持续时间，设备编号，报警类型，未报警的时间
		Map<String, Object> map = new HashMap<String, Object>();
		long minute = 0;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		LevelTimeBean bean = messageBiz.queryLevelTime();
		int one = bean.getLevelOne(), two = bean.getLevelTwo(), three = bean.getLevelThree();
		// 求相差多少分钟
		String initialAlarmTime= oldMap.get("initialAlarmTime").toString();
		Date date = format.parse(initialAlarmTime);
		minute = (System.currentTimeMillis() - date.getTime()) / 1000 / 60;

		if (one < minute && minute <= two) {
			map.put("msgAlertLevel", DictionaryEnums.LEVEL_ONE.getCode());
		} else if (two < minute && minute <= three) {
			map.put("msgAlertLevel",
					DictionaryEnums.LEVEL_ONE.getCode() + "," + DictionaryEnums.LEVEL_SECOND.getCode());
		} else if (three < minute) {
			map.put("msgAlertLevel", DictionaryEnums.LEVEL_ONE.getCode() + "," + DictionaryEnums.LEVEL_SECOND.getCode()
					+ "," + DictionaryEnums.LEVEL_THIRTH.getCode());
		}
		if (map != null && map.size() > 0) {
			map.put("deviceNo", deviceNo);
			List<Map<String, Object>> listTelMap = userService.selectTelByAlarmLevel(map);
			if (listTelMap != null && listTelMap.size() > 0) {
				String[] phones = new String[listTelMap.size()];
				for (int i = 0; i < listTelMap.size(); i++) {
					if (listTelMap.get(i).get("telephone").toString() != "") {
						phones[i] = listTelMap.get(i).get("telephone").toString();
					}
				}
				String alarmTypeMsg = null;
				List<Dictionary> listDic = dictionaryService
						.queryDictionaryByParentId(DictionaryEnums.ALARM_TYPE.getCode());
				String message = null;
				if (listDic != null) {
					for (Dictionary dictionary : listDic) {
						if (dictionary.getDictionaryKey() == alarmType) {
							alarmTypeMsg = DictionaryEnums.find(dictionary.getDictionaryKey()).getMsg();
							if (alarmTypeMsg != null) {
								message = "【浙江小桥流水】您设备编号为" + deviceNo + "的设备出现" + alarmTypeMsg + "故障，持续" + minute
										+ "分钟，检测为" + getMsgAlertLevel(map.get("msgAlertLevel").toString())
										+ "报警，请联系工作人员前去处理！";
								for (int j = 0; j < phones.length; j++) {
									messageService.sendMessage(phones[j], message, alarmType);
								}
							}
						}
					}
				}

			} else {
				logger.error("未找到报警接收的手机");
			}
		}
	}

	private void alarm(SimpleDateFormat format, int alarmType, String deviceNo, Map<String, Object> map)
			throws Exception {
		int times = 0;
		if (map.get("times") != null && map.get("times") != "") {
			times = Integer.parseInt(map.get("times").toString());
		}
		AlarmExample example = new AlarmExample();
		example.createCriteria().andDeviceNoEqualTo(deviceNo).andAlarmTypeEqualTo(alarmType)
				.andAlarmStatusEqualTo(DictionaryEnums.ALARM.getCode());
		List<AlarmBean> list = alarmService.selAlarmByExample(example);// 查询数据库是否存在该条报警记录

		// 存在，并且报警次数小于等于3次，发短信
		if (list != null && list.size() > 0) {
			for (AlarmBean alarmBean : list) {
				if (alarmBean.getTimes() < 3) {
					if (alarmBean.getTimes() == 0) {
						if (Integer.parseInt(map.get("minute").toString()) >= Integer
								.parseInt(map.get("intervalTime").toString())) {
							times = times + 1;
							alarmService.updateAlarmData(deviceNo, alarmType, DictionaryEnums.ALARM, times);
							sendMessage(alarmType, deviceNo, times, map);
						} else {
							alarmService.updateAlarmData(deviceNo, alarmType, DictionaryEnums.ALARM, times);
						}
					} else {
						int minute = Integer.parseInt(map.get("minute").toString());
						int yu = minute - Integer.parseInt(map.get("intervalTime").toString())*alarmBean.getTimes();
						if (yu >= Integer
								.parseInt(map.get("intervalTime").toString())) {
							times = times + 1;
							alarmService.updateAlarmData(deviceNo, alarmType, DictionaryEnums.ALARM, times);
							sendMessage(alarmType, deviceNo, times, map);
						} else {
							alarmService.updateAlarmData(deviceNo, alarmType, DictionaryEnums.ALARM, times);
						}
					}
				}else if(alarmBean.getTimes() == 3){
					alarmService.updateAlarmData(deviceNo, alarmType, DictionaryEnums.ALARM, times);
				}
			}
		} else {
			// 不存在，添加一条报警记录
			alarmService.insertAlarm(deviceNo, alarmType, times);
			if (0 >= Integer.parseInt(map.get("intervalTime").toString())) {
				sendMessage(alarmType, deviceNo, times, map);
			}
		}

	}

	// 得到报警等级
	public String getMsgAlertLevel(String msgAlertLevel) {
		String msgLevel = null;
		String msgCode = msgAlertLevel.split(",")[msgAlertLevel.split(",").length - 1];
		msgLevel = DictionaryEnums.find(Integer.parseInt(msgCode)).getMsg();
		return msgLevel;
	}

}
